<!-- 职位体系管理表格 -->
<template>
  <a-modal
    width="80%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
  >
    <template #title>
      <div>职位列表</div>
    </template>
    <div class="main-list" style="flex: 4; padding: 0 20px; overflow: auto">
      <div class="header" style="display: flex; justify-content: space-between">
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入职位名称"
          search-button
          v-model="nameSearch"
          @search="onSearch"
          @press-enter="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </div>
      <table-turn :table-data="getTableData" :args="args" ref="tableRef">
        <a-table-column :width="80">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :title="item.name"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.code"
          :width="200"
          :sortable="{
            sortDirections: ['ascend', 'descend']
          }"
          :fixed="
            item.code === 'C2818BAA63AE848AA845DA2E81ECB1843' ? 'left' : ''
          "
        >
          <!-- 标准职位编码 -->
          <template v-if="item.code === 'positonStandCode'" #cell="{}">
          </template>

          <!-- 职位类别 -->
          <template
            v-else-if="item.code === 'C63EC32DCE9CC4BE6AC7649E23234A542'"
            #cell="{ record }"
          >
            {{
              positionTypeList.find(
                (item: any) =>
                  item.id == record['C63EC32DCE9CC4BE6AC7649E23234A542']
              )?.name
            }}
          </template>

          <!-- 职位层级 -->
          <template
            v-else-if="item.code === 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC'"
            #cell="{ record }"
            ><div>
              {{
                positionLevelList.find(
                  (item: any) =>
                    item.id == record['C9A9EF3DFFFC84AAFB97443DEE8E5B8CC']
                )?.name
              }}
            </div>
          </template>

          <!-- 是否特殊工种 -->
          <template
            v-else-if="item.code === 'CB4163C72FA5E45D38302983E8A66801E'"
            #cell="{ record }"
          >
            {{ record.positonSpecialProfession === 1 ? '是' : '否' }}
          </template>

          <!-- 是否关键职位 -->
          <template
            v-else-if="item.code === 'CE183DF5A547A4728A60F9AFDF3C53194'"
            #cell="{ record }"
          >
            {{ record.positonKeyJob === 1 ? '是' : '否' }}
          </template>

          <!-- 公司 -->
          <template
            v-else-if="item.code === 'CA8ABCC1480744557B3014C3454465A7E'"
            #cell="{ record }"
          >
            {{
              deptList.find(
                (item: any) =>
                  item.id == record['CA8ABCC1480744557B3014C3454465A7E']
              )?.name
            }}
          </template>

          <!-- 职位所属部门 -->
          <template
            v-else-if="item.code === 'CED44AC9966904CD1AB546D309903727C'"
            #cell="{ record }"
          >
            {{
              deptList.find(
                (item: any) =>
                  item.id == record['CED44AC9966904CD1AB546D309903727C']
              )?.name
            }}
          </template>

          <!-- 关联职务 -->
          <template
            v-else-if="item.code === 'C1F5AA49A78EC4B4FBD487F4D5887E576'"
            #cell="{ record }"
          >
            {{
              jobList.find(
                (item: any) =>
                  item.id == record['C1F5AA49A78EC4B4FBD487F4D5887E576']
              )?.name
            }}
          </template>

          <!-- 关联标准职务 -->
          <template v-else-if="item.code === 'positonStandRelated'" #cell="{}">
          </template>

          <!-- 选择职位说明书模板 -->
          <template
            v-else-if="item.code === 'C8B68CCFE6DAB49D088E663E467BFAB34'"
            #cell="{}"
          >
          </template>
          <!-- 职位序列 -->
          <template
            v-else-if="item.code === 'CC0DAA8E0695A48489672B3E3B4DE8F1B'"
            #cell="{}"
          >
          </template>
          <!-- 职级范围 -->
          <template v-else-if="item.code === 'positonRange'" #cell="{}">
          </template>
          <!-- 是否设为标准职位 -->
          <template
            v-else-if="item.code === 'C50267C6B8E104B0C91EDD25BCAE35609'"
            #cell="{ record }"
          >
            {{ record.positionSetStandPosition === 1 ? '是' : '否' }}
          </template>
        </a-table-column>
        <a-table-column
          title="是否启用"
          :width="100"
          fixed="right"
          data-index="enable"
        >
          <template #cell="{ record }">
            <span
              :style="{
                color: record.enable === 1 ? '' : 'red'
              }"
            >
              {{ record.enable === 1 ? '是' : '否' }}
            </span>
          </template>
        </a-table-column>
      </table-turn>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { controldataTreeFilter, flatTree } from '@/utils/utils';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import {
  GetPositionTypeList,
  GetPositionLevelList
} from '@/apis/management/organization/baseSetting';
import { GetJobList } from '@/apis/management/organization/positionManagement';
import { GetHeaderSetting, PostHeaderSetting } from '@/apis/management/base';
import { GetBusinessModalData } from '@/apis/controltotal';
import { Message } from '@arco-design/web-vue';
import mitter from '@/utils/mitt';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框，
    selectedIds: number[]; // 选中的ids
  }>(),
  {
    visible: false
  }
);
const emit = defineEmits(['update:visible', 'positionEmit']);
// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

watch(
  () => props.visible,
  (newVal: any) => {
    if (newVal) {
      tableRef.value.selectedList = props.selectedIds;
    }
  }
);

// 新增表头
const addHeader = async () => {
  try {
    const heads: any = [];
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCE54A4F24B2A6453A8A4B8E9397C36A63'
    })) as any;

    let sort = 0;
    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail.forEach((item2: any, index2: number) => {
        delete item2.isDefault;
        heads.push({
          collectionName: cnName,
          collectionCode: subCode,
          code: item2.ctlCode,
          name: item2.ctlCnName,
          isDefault: true,
          userId: +(localStorage.getItem('userId') as string),
          type: 2,
          sort,
          isMust: forbidList.includes(item2.ctlCode) ? true : false,
          ...item2
        });
        sort++;
      });
    });
    await PostHeaderSetting({
      heads
    });
    // arr.forEach(async ({ code, name, isDefault }: any) => {
    //   await PostPositionSetting({
    //     code,
    //     name,
    //     isDefault,
    //     type: 2,
    //     userId: +(localStorage.getItem('userId') as string)
    // });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

let tableRef = ref(); // 储存table的ref

let modalVisiable = ref(false); // 判断是否点击新增按钮

const dataFilter = (data: any) => {
  const arr = data.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.positionDetailData)
  }));
  return arr;
};
const nameSearch = ref(''); // 储存职位名称
let positionType = ref(''); // 储存旁边导航栏的职位类型
watchEffect(() => {
  // 响应旁边导航栏点击查找对应的职位类型
  mitter.on('positionTreeSelect', (res: any) => {
    positionType.value = res;
    tableRef.value.loadData();
  });
});
// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    const res: any = await GetPosition({
      ...pageData,
      name: nameSearch.value,
      positionType: positionType.value
      // typeId: 0
    });
    res.content = dataFilter(res.content);
    console.log('====================================zcxz');
    console.log(res.content);
    console.log('====================================');
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
// 搜索框
const onSearch = () => {
  tableRef.value.loadData();
};

let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let positionTypeList = ref([]); // 储存当前职位类型数据
let deptList = ref([]); // 部门类型数据
let jobList = ref([]); // 职务类型
let positionLevelList = ref([]); // 职位层级数据
let forbidList = [
  'C2818BAA63AE848AA845DA2E81ECB1843',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'CB25F6DA9F83C4424BBC37E8756BB871E'
]; // 必选的表头 职位名称，职位类型, 职位编码

const getData = async () => {
  try {
    const res: any = await Promise.all([
      // 获取表头
      GetHeaderSetting({
        type: 2,
        userId: +(localStorage.getItem('userId') as string)
      }),
      // 获取职位类型数据
      GetPositionTypeList({}),
      // 获取部门类型
      GetOrganizationList({}),
      // 获取职务管理数据
      GetJobList({
        page: 1,
        size: -1
      }),
      // 获取职位层级数据
      GetPositionLevelList({
        page: 1,
        size: -1
      })
    ]);
    headerSetting.value = res[0].header;
    if (headerSetting.value.length === 0) {
      addHeader();
    }

    // 扁平化树状数据
    positionTypeList.value = flatTree(res[1]);
    deptList.value = flatTree(res[2]);
    jobList.value = res[3].content;
    positionLevelList.value = res[4].content;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

// 在表格上显示的表头
const selectedHeader = computed(() => {
  let arr: any = [];
  headerSetting.value.forEach((item1: any) => {
    arr = [
      ...arr,
      ...item1.heads.filter((item2: any) => item2.isDefault === true)
    ];
  });
  arr.sort((a: any, b: any) => a.sort - b.sort);
  return arr;
});
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 保存
const handleOk = () => {
  emit('positionEmit', selectedList.value, selectedListData.value);
  // 清空选择器
  // tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  // 清空选择器
  // tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  emit('update:visible', false);
};
</script>

<style scoped lang="less">
.header {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 20px;
  height: 35px;
  &-front {
    position: relative;
    line-height: 30px;
    margin-right: 20px;
  }
}
</style>
